#include "transcoding.h"

// 函数用于将 UTF-8 编码字符串转换为 UCS-2 编码字符串
// 返回转换后 UCS-2 编码字符串的长度，如果转换失败则返回 -1
int utf8_to_ucs2(const unsigned char *in, unsigned short *out, int max_out_len)
{
    unsigned short *outoffset = out;
    unsigned short *outend = out + max_out_len / 2;
    int ret = 0;

    while (*in != '\0' && ret + 1 < max_out_len / 2)
    {
        unsigned short ucs2_code = 0;

        if (0x00 == (*in & 0x80))
        {
            // 1 字节 UTF-8 字符
            ucs2_code = (unsigned short)*in;
            in++;
        }
        else if (0xc0 == (*in & 0xe0) && 0x80 == (*(in + 1) & 0xc0))
        {
            // 2 字节 UTF-8 字符
            ucs2_code = ((*in & 0x1f) << 6) | (*(in + 1) & 0x3f);
            in += 2;
        }
        else if (0xe0 == (*in & 0xf0) && 0x80 == (*(in + 1) & 0xc0) &&
                 0x80 == (*(in + 2) & 0xc0))
        {
            // 3 字节 UTF-8 字符
            ucs2_code = ((*in & 0x0f) << 12) | ((*(in + 1) & 0x3f) << 6) |
                        (*(in + 2) & 0x3f);
            in += 3;
        }
        else
        {
            // 非法 UTF-8 字符
            return -1;
        }

        // 将 UCS-2 编码字符写入输出缓冲区
        if (outoffset < outend)
        {
            *outoffset++ = ucs2_code;
            ret++;
        }
        else
        {
            // 输出缓冲区空间不足
            return -1;
        }
    }

    // 返回转换后的 UCS-2 编码字符串的长度
    return ret;
}
